package com.tib.utils;

import com.tib.em.StatusCodeEnum;

import java.util.Date;

/**
 *服务器端响应json转换类。
 *
 * @author caoxianghua
 * @create 2021-12-22 14:24
 **/
public class JsonResponse implements java.io.Serializable, Cloneable {

    private static final long serialVersionUID = 1L;

    //状态码
    int code;

    //响应消息
    String msg;

    // 数据
    Object data;

    //时间戳
    long timestamp;

    public JsonResponse() {
        super();
        this.code = StatusCodeEnum.SUCCESS.getCode();
        this.msg = StatusCodeEnum.SUCCESS.getDesc();
        this.data = null;
        this.timestamp = new Date().getTime();
    }

    /**
     * 实例一个成功的响应
     *
     * @return 响应实例
     */
    public static JsonResponse newOk() {
        JsonResponse response = new JsonResponse();
        response.setCode(StatusCodeEnum.SUCCESS.getCode());
        response.setMsg(StatusCodeEnum.SUCCESS.getDesc());
        return response;
    }

    /**
     * 实例一个包括数据的成功响应
     *
     * @param data 数据
     * @return 响应实例
     */
    public static JsonResponse newOk(Object data) {
        JsonResponse response = new JsonResponse();
        response.setCode(StatusCodeEnum.SUCCESS.getCode());
        response.setMsg(StatusCodeEnum.SUCCESS.getDesc());
        response.setData(data);
        return response;
    }

    /**
     * 实例化一个系统错误的响应
     * @param msg 自定义的错误信息
     * @return 响应实例
     */
    public static JsonResponse newError(String msg) {
        JsonResponse response = new JsonResponse();
        response.setCode(StatusCodeEnum.CUSTOM_ERROR.getCode());
        response.setMsg(msg);
        return response;
    }

    /**
     * 通过系统内置枚举实例化一个系统错误的响应
     * @param statusEnum 错误枚举
     * @return 响应实例
     */
    public static JsonResponse newError(StatusCodeEnum statusEnum) {
        JsonResponse response = new JsonResponse();
        response.setCode(statusEnum.getCode());
        response.setMsg(statusEnum.getDesc());
        return response;
    }


    public int getCode() {
        return code;
    }

    public JsonResponse setCode(int code) {
        this.code = code;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public JsonResponse setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Object getData() {
        return this.data;
    }

    public JsonResponse setData(Object data) {
        this.data = data;
        return this;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public JsonResponse setTimestamp(long timestamp) {
        this.timestamp = timestamp;
        return this;
    }

    @Override
    public String toString() {
        return "JsonResponse [code=" + code + ", msg=" + msg + ", data=" + data + ", timestamp=" + timestamp + "]";
    }


}

